package leetcode.Hot100;

import leetcode.ListNode;

/**
 * @author Cheng Jun
 * Description: 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 *
 *
 * @version 1.0
 * @date 2021/11/14 16:08
 */
public class mergeTwoLists {

    // 提示：
    // 1.两个链表的节点数目范围是 [0, 50]
    // 2.-100 <= Node.val <= 100
    // 3.l1 和 l2 均按 非递减顺序 排列
    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode listNode = new ListNode();
        ListNode pointer = listNode;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                pointer.next = l1;
                l1 = l1.next;
            } else {
                pointer.next = l2;
                l2 = l2.next;
            }
            pointer = pointer.next;
        }
        // 当 l1 用完了，把 l2 放到 pointer.next
        if (l1 == null) pointer.next = l2;
        // 当 l2 用完了，把 l1 放到 pointer.next
        if (l2 == null) pointer.next = l1;
        return listNode.next;
    }

    // 似乎没有太大优化
    public static ListNode mergeTwoLists1(ListNode l1, ListNode l2) {
        ListNode listNode = new ListNode();
        ListNode pointer = listNode;
        while (l1 != null || l2 != null) {
            if (l1 == null) {
                pointer.next = l2;
                break;
            }
            if (l2 == null) {
                pointer.next = l1;
                break;
            }
            if (l1.val <= l2.val) {
                pointer.next = l1;
                l1 = l1.next;
            } else {
                pointer.next = l2;
                l2 = l2.next;
            }
            pointer = pointer.next;
        }
        return listNode.next;
    }
}
